<template>
  <div>
    <el-dialog :visible="showDialog" @close="closeFn">
      <el-form ref="form" :rules="rules" :model="formData">
        <el-form-item prop="title" label="标题" label-width="50px" label-position="left">
          <el-input v-model="formData.title" />
        </el-form-item>
        <el-form-item prop="desc" label="描述" label-width="50px" label-position="left">
          <el-input v-model="formData.desc" type="textarea" />
        </el-form-item>
        <el-form-item label="封面" label-width="50px" label-position="left">
          <!-- 上传头像 -->
          <updateImages ref="uploadImg1" />
          <el-input v-model="formData.image" />
        </el-form-item>
      </el-form>

      <!-- 底部 -->
      <el-row type="flex" justify="end">
        <el-button size="small" type="primary" @click="confirmFn">确定</el-button>
        <el-button size="small" @click="closeFn">取消</el-button>
      </el-row>
    </el-dialog>

  </div>
</template>

<script>
import updateImages from '@/views/types/components/updateImages.vue'
import { addTypes, getTypesDetails, updateTypes } from '@/api/types'
export default {
  components: {
    updateImages
  },
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        desc: '',
        image: '',
        title: ''
      },
      rules: {
        title: [
          {
            required: true, message: '该项不能为空', trigger: 'blur'
          }
        ],
        desc: [
          {
            required: true, message: '该项不能为空', trigger: 'blur'
          }
        ]

      }
    }
  },
  methods: {
    async confirmFn() {
      // 校验正确
      this.$refs.form.validate()
      const uploadImage = this.$refs.uploadImg1
      // 当图片的上传进度小于100 大于0的时候提示图片还未上传完成
      if (uploadImage.percent < 100 && uploadImage.percent > 0) {
        return this.$message({
          type: 'warning',
          message: '请等待图片上传成功后再保存'
        })
      }
      this.formData.image = uploadImage.fileList[0] && uploadImage.fileList[0].url

      if (this.formData.id) {
        // 确认编辑数据
      // 数据编辑
        await updateTypes(this.formData)
      } else {
        // 确认新增
        await addTypes(this.formData)
      }
      // 关闭弹窗、清空列表和校验
      this.closeFn()

      // 子传父实现刷新页面
      this.$emit('addEvent')
    },
    closeFn() {
      this.$emit('update:showDialog', false)
      // 清空数据
      this.formData = {
        desc: '',
        image: '',
        title: ''
      }

      // 清空校验
      this.$refs.form.resetFields()
    },
    async updateTypes(id) {
      // 加载
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      // 数据回显
      const res = await getTypesDetails(id)
      this.formData = res.data
      // console.log(res)

      // 加载结束
      loading.close()
    }
  }
}
</script>

<style>

</style>
